<template>
  <div class="create-post-page">
    <h4>新建文章</h4>
    <upload
      action="api/upload"
      :beforeUpload="beforeUpload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
    >
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <span class="sr-only">Loading...</span>
          </div>
          <h2>正在上传</h2>
        </div>
      </template>

      <template #uploaded="dataProps">
        <div class="uploaded-area">
          <img :src="dataProps.uploadedData.data.url" />
        </div>
      </template>
    </upload>
    <validate-form @form-submit="onSubmit">
      <div class="mb-3">
        <div class="form-label">文章标题：</div>
        <validate-input :rules="titleRules" v-model="titleVal" type="text" />
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <validate-input :rules="contentRules" v-model="contentVal" tag="textarea" rows="10" />
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">发表文章</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useStore } from 'vuex'
import { RuleProps, ResponseType } from "@/types";
import ValidateForm from "@/components/ValidateForm.vue";
import ValidateInput from "@/components/ValidateInput.vue";
import Upload from "@/components/Upload.vue";
import message from '@/components/message/index';
import { beforeUploadCheck } from "@/utils";

const titleVal = ref('')
const contentVal = ref('')
const titleRules: RuleProps[] = [
  { type: 'required', message: '文章标题不能为空' },
]
const contentRules: RuleProps[] = [
  { type: 'required', message: '文章详情不能为空' }
]

const beforeUpload = (file: File) => {
  const result = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1 })
  const { passed, error } = result
  if (error === 'format') {
    message('上传图片只能是 JPG/PNG 格式!', 'error')
  }
  if (error === 'size') {
    message('上传图片大小不能超过 1Mb', 'error')
  }
  return passed
}

const onSubmit = (result: boolean) => {
  if (result) {

  }
}
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}

.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.uploaded-area {
  position: relative;
}

.uploaded-area:hover h3 {
  display: block;
}

.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>